<?php

class Vega_Dispatcher
{
    protected $_router = null;
    
    /**
     * The default router class
     */
    protected $_routerClass = 'Vega_Router_Standard';

    /**
     * App object
     * 
     * @var Vega_App
     */
    protected $_app = null;


    public function __construct(Vega_App $app)
    {
        $this->_app = $app;
    }

    /**
     * Returns a router object. If it was not declared yet, create it.
     *
     * @return Vega_Router_Abstract
     */
    public function getRouter()
    {
        if (null === $this->_router)
        {
            $routerClass = $this->_routerClass;
            
            $request = Vega_App::getInstance()->getRequest();
            $this->_router = new $routerClass($request);
        }
        return $this->_router;
    }
    
    /**
     * Sets router
     *
     * @param Vega_Router_Abstract $router
     * @return Vega_Dispatcher
     */
    public function setRouter(Vega_Router_Abstract $router)
    {
        $this->_router = $router;
        return $this;
    }
    
    /**
     * Sets router class
     *
     * @param string $routerClass
     * @return Vega_Dispatcher
     */
    public function setRouterClass($routerClass)
    {
        $this->_routerClass = $routerClass;
        return $this;
    }
    
    /**
     * Returns router class
     *
     * @return string
     */
    public function getRouterClass()
    {
        return $this->_routerClass;
    }
    
    /**
     * Does the dispatch job
     *
     * @return mixed
     */
    public function dispatch()
    {
        $router   = $this->getRouter();
        $request  = $router->route();
        
        $response = $this->_app->getResponse();
        $output   = null;
        
        //do 
        //{   
            $module = $this->_app->loadModule($request, $response);
            
            if (!$module)
            {
                // the module does not exist or can not be loaded. Return a 404.
                $response->setResponseCode(404);				
				
				throw new Exception('', 404);
                return $response;
            }
            
            try 
            {
                $output = $module->dispatch();
            }
            catch (Vega_Module_Exception $e)
            {
                $response->setResponseCode($e->getCode());
            }
            catch (Exception $e)
            {
                throw $e;
            }

            $response->setOutput($output);
            
        //} while ($request->isDispatched() === false);
        
        return $response;
    }
    
}

